#pragma once
#include <iostream>
#include <string>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "Common.hpp"

class InetAddr
{
private:
    void Port_N2H()
    {
        _port = ntohs(_net_addr.sin_port);
    }

    void IP_N2H()
    {
        char buf[20];
        ::inet_ntop(AF_INET, &_net_addr.sin_addr, buf, sizeof(buf));
        _ip = buf;
    }

public:
    InetAddr()
    {
    }
    InetAddr(const struct sockaddr_in &addr) : _net_addr(addr)
    {
        Port_N2H();
        IP_N2H();
    }
    InetAddr(uint16_t port) : _port(port)
    {
        _net_addr.sin_family = AF_INET;
        _net_addr.sin_port = htons(_port);
        // _net_addr.sin_addr.s_addr = ::inet_addr(_ip.c_str());
        _net_addr.sin_addr.s_addr = INADDR_ANY; // 上面这一句可以改成这个，表示允许任何远程主机连接
    }

    bool operator==(const InetAddr &_addr)
    {
        return (_ip == _addr._ip);
    }

    struct sockaddr *GetSockaddr() { return CONV(&_net_addr); }
    socklen_t GetSockaddrLen() { return sizeof(_net_addr); }
    std::string GetStrIp() const { return _ip; }
    uint16_t GetPort() const { return _port; }
    std::string GetStrIpPort() const { return GetStrIp() + ":" + std::to_string(GetPort()); }

    void SetAddr(const sockaddr_in &addr, socklen_t &len)
    {
        _net_addr = addr;
        (void)len;
        Port_N2H();
        IP_N2H();
    }

    ~InetAddr()
    {
    }

private:
    std::string _ip;
    uint16_t _port;
    struct sockaddr_in _net_addr;
};